package com.yj.forum.controller;

import com.yj.forum.common.AppConfig;
import com.yj.forum.common.AppResult;
import com.yj.forum.common.ResultCode;
import com.yj.forum.model.User;
import com.yj.forum.services.IUserService;
import com.yj.forum.utils.MD5Util;
import com.yj.forum.utils.StringUtil;
import com.yj.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags = "用户接口")
@Slf4j
// 标识为了个Controller并且响应时返回Body中的数据
@RestController
//路径映射
@RequestMapping("/user")
public class UserController {
    //service注入
    @Resource
    private IUserService userService;

    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 用户昵称
     * @param password 用户密码
     * @param passwordRepeat 确认密码
     * @return 成功
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public AppResult register(@ApiParam("用户名") @RequestParam(value = "username" ) String username,
                              @ApiParam("用户昵称") @RequestParam(value = "nickname" ) String nickname,
                              @ApiParam("用户密码") @RequestParam(value = "password" ) String password,
                              @ApiParam("确认密码") @RequestParam(value = "passwordRepeat") String passwordRepeat)  {
        //参数校验
        if(StringUtil.isEmpty(username)
        || StringUtil.isEmpty(nickname)
        || StringUtil.isEmpty(password)
        || StringUtil.isEmpty(passwordRepeat)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出参数校验失败异常
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //密码确认
        if(!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 基本信息赋值
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //  加密密码
        String salt = UUIDUtil.UUID_32();
        user.setSalt(salt);
        String ciphertext = MD5Util.md5Salt(password, salt);
        user.setPassword(ciphertext);

        userService.createNormalUser(user);
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 用户密码
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(@ApiParam("用户名") @RequestParam(value = "username" ) String username,
                           @ApiParam("用户密码") @RequestParam(value = "password" ) String password ,
                           HttpServletRequest request) {
        //非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //调用service
        User user = userService.login(username, password);
        // 获取Session
        HttpSession session =  request.getSession(true);
        // 把User设置到Session中 
        session.setAttribute(AppConfig.USER_SESSION , user);


        return AppResult.success();

    }

    /**
     * 用户退出
     * @return 成功状态
     */
    @ApiOperation("用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        //获取session
        HttpSession session = request.getSession();
        if( session != null) {
            // 注销session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 获取用户详情
     * @param id 用户id
     * @return 用户详情
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {
        User user = null;
        //id 为空，返回当前登录⽤⼾
        if( id == null) {
//            // 获取Session中的⽤⼾信息
            HttpSession session = request.getSession();
            //拦截器已经做了
//            if(session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
//                return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
//            }
            user = (User) session.getAttribute(AppConfig.USER_SESSION);

        } else {
            // id 不为空，根据⽤⼾Id从数据库中查询⽤⼾信息
            user = userService.selectById(id);
        }
        return AppResult.success(user);
    }
    /**
     * 修改个⼈信息
     * @param username ⽤⼾名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个⼈简介
     * @return AppResult
     */
    @ApiOperation("修改个⼈信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("⽤⼾名") @RequestParam(value = "username", required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                                @ApiParam("昵称") @RequestParam(value = "gender", required = false) Byte gender,
                                @ApiParam("昵称") @RequestParam(value = "email", required = false) String email,
                                @ApiParam("昵称") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                                @ApiParam("昵称") @RequestParam(value = "remark", required = false) String remark) {
        //获取对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //对参数做⾮空校验（全部都为空，则返回错误描述）
         if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname) && gender == null
             && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark) ) {
             // 返回错误信息
             return AppResult.failed("请输⼊要修改的内容");
         }
        // 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // ⽤⼾Id
        updateUser.setUsername(username); // ⽤⼾名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个⼈简介

        //调用service
        userService.modifyInfo(updateUser);
        //更新session
        user = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);


        return AppResult.success(user);

    }

    /**
     *修改密码
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @param passwordRepeat 确认密码
     * @return AppResult
     */
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码")@RequestParam("oldPassword") String oldPassword,
                                    @ApiParam("新密码")@RequestParam("newPassword") String newPassword,
                                    @ApiParam("确认密码")@RequestParam("passwordRepeat") String passwordRepeat) {
        //非空校验
        if(StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //新密码与确认密码是否相同
        if(!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //拿取用户
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        //销毁session,让用户重新登录
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }
}

